import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Button,
  Input,
  Label,
  Text,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  Spinner,
} from 'packages/ui-shared/src/atoms';
import { AuditLogService, AuditAction } from '@packages/shared';

// 用户注册接口
interface RegisterForm {
  studentId: string;
  name: string;
  gender: string;
  age: number;
  major: string;
  className: string;
  admissionYear: string;
  phone: string;
  email: string;
  password: string;
  confirmPassword: string;
  address: string;
}

// 用户数据接口
interface UserData {
  id: number;
  studentId: string;
  name: string;
  gender: string;
  age: number;
  major: string;
  class: string;
  admissionYear: string;
  phone: string;
  email: string;
  pwd: string;
  address: string;
  status: string;
  role: string;
  mfaVerified: boolean;
}

export default function Register() {
  const navigate = useNavigate();
  const [form, setForm] = useState<RegisterForm>({
    studentId: '',
    name: '',
    gender: '男',
    age: 18,
    major: '',
    className: '',
    admissionYear: new Date().getFullYear().toString(),
    phone: '',
    email: '',
    password: '',
    confirmPassword: '',
    address: '',
  });
  const [msg, setMsg] = useState('');
  const [loading, setLoading] = useState(false);
  const [showVerification, setShowVerification] = useState(false);
  const [verificationCode, setVerificationCode] = useState('');
  const [userInputCode, setUserInputCode] = useState('');
  const [countdown, setCountdown] = useState(0);

  // 专业选项
  const majors = ['计算机科学与技术', '软件工程', '数据科学', '人工智能', '数学', '物理', '化学', '生物', '文学院', '历史学院'];
  // 性别选项
  const genders = ['男', '女', '其他'];

  // 生成验证码
  const generateCode = () => {
    return Math.floor(100000 + Math.random() * 900000).toString();
  };

  // 发送验证码
  const sendVerificationCode = (phone: string) => {
    const code = generateCode();
    setVerificationCode(code);
    setCountdown(60);
    setShowVerification(true);

    // 模拟发送验证码
    console.log(`发送验证码到 ${phone}: ${code}`);

    // 倒计时
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return code;
  };

  // 验证表单
  const validateForm = (): boolean => {
    if (!form.studentId || !form.name || !form.phone || !form.password || !form.confirmPassword) {
      setMsg('请填写所有必填字段');
      return false;
    }

    if (form.password !== form.confirmPassword) {
      setMsg('两次输入的密码不一致');
      return false;
    }

    if (form.password.length < 6) {
      setMsg('密码长度至少6位');
      return false;
    }

    if (!/^1[3-9]\d{9}$/.test(form.phone)) {
      setMsg('请输入正确的手机号');
      return false;
    }

    return true;
  };

  // 注册用户
  const handleRegister = async () => {
    if (!validateForm()) {
      return;
    }

    setLoading(true);
    setMsg('');

    try {
      // 检查手机号是否已注册
      const existingUsers = localStorage.getItem('students');
      if (existingUsers) {
        const users: UserData[] = JSON.parse(existingUsers);
        const phoneExists = users.some(user => user.phone === form.phone);
        const studentIdExists = users.some(user => user.studentId === form.studentId);

        if (phoneExists) {
          setMsg('该手机号已注册');
          setLoading(false);
          return;
        }

        if (studentIdExists) {
          setMsg('该学号已存在');
          setLoading(false);
          return;
        }

        // 创建新用户
        const newUser: UserData = {
          id: users.length > 0 ? Math.max(...users.map(user => user.id)) + 1 : 1,
          studentId: form.studentId,
          name: form.name,
          gender: form.gender,
          age: form.age,
          major: form.major,
          class: form.className,
          admissionYear: form.admissionYear,
          phone: form.phone,
          email: form.email,
          pwd: form.password, // 注意：实际应用中应加密存储密码
          address: form.address,
          status: '在读',
          role: 'user',
          mfaVerified: false
        };

        // 添加到用户列表
        const updatedUsers = [...users, newUser];
        localStorage.setItem('students', JSON.stringify(updatedUsers));

        // 记录注册成功的审计日志
        await AuditLogService.log(
          newUser.id,
          newUser.name,
          newUser.role,
          AuditAction.REGISTER,
          '用户注册成功',
          true,
          { phone: form.phone }
        );

        setMsg('注册成功，请登录');
        setTimeout(() => {
          navigate('/login');
        }, 1500);
      } else {
        // 如果没有现有用户，创建第一个用户
        const firstUser: UserData = {
          id: 1,
          studentId: form.studentId,
          name: form.name,
          gender: form.gender,
          age: form.age,
          major: form.major,
          class: form.className,
          admissionYear: form.admissionYear,
          phone: form.phone,
          email: form.email,
          pwd: form.password, // 注意：实际应用中应加密存储密码
          address: form.address,
          status: '在读',
          role: 'user',
          mfaVerified: false
        };

        localStorage.setItem('students', JSON.stringify([firstUser]));

        // 记录注册成功的审计日志
        await AuditLogService.log(
          firstUser.id,
          firstUser.name,
          firstUser.role,
          AuditAction.REGISTER,
          '用户注册成功',
          true,
          { phone: form.phone }
        );

        setMsg('注册成功，请登录');
        setTimeout(() => {
          navigate('/login');
        }, 1500);
      }
    } catch (error) {
      // 记录注册异常的审计日志
      await AuditLogService.log(
        0,
        'Unknown',
        'guest',
        AuditAction.REGISTER,
        '注册异常',
        false,
        { phone: form.phone, error: '系统异常' }
      );
      setMsg('注册失败，请重试');
    }

    setLoading(false);
  };

  // 验证验证码
  const verifyCode = () => {
    if (userInputCode === verificationCode) {
      setShowVerification(false);
      handleRegister();
    } else {
      setMsg('验证码错误，请重试');
    }
  };

  // 重新发送验证码
  const resendCode = () => {
    if (countdown === 0) {
      sendVerificationCode(form.phone);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-50 font-sans">
      {/* 装饰性背景元素 */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -left-40 w-80 h-80 bg-blue-400 rounded-full opacity-10 blur-3xl"></div>
        <div className="absolute top-1/3 -right-40 w-80 h-80 bg-indigo-400 rounded-full opacity-10 blur-3xl"></div>
        <div className="absolute bottom-0 left-1/3 w-80 h-80 bg-purple-400 rounded-full opacity-10 blur-3xl"></div>
      </div>

      {/* 注册卡片 */}
      <div className="relative w-full max-w-md p-8 bg-white rounded-2xl shadow-xl border border-gray-100 overflow-hidden z-10 transform transition-all duration-300 hover:shadow-2xl">
        {/* 卡片顶部装饰条 */}
        <div className="absolute top-0 left-0 right-0 h-1.5 bg-gradient-to-r from-green-500 via-teal-500 to-cyan-500"></div>

        {/* 卡片内容 */}
        <div className="pt-6 space-y-8">
          <div className="text-center space-y-2">
            {/* 品牌图标 */}
            <div className="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-green-600 to-teal-600 rounded-xl flex items-center justify-center shadow-lg">
              <Text className="text-white text-2xl font-bold">R</Text>
            </div>

            <Text className="text-2xl font-bold text-gray-900 tracking-tight">用户注册</Text>
            <Text className="text-gray-500 max-w-xs mx-auto">创建您的账户以访问系统</Text>
          </div>

          <div className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              {/* 学号输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="studentId"
                  className="block text-sm font-medium text-gray-700"
                >
                  学号 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="studentId"
                  name="studentId"
                  type="text"
                  value={form.studentId}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, studentId: e.target.value }))
                  }
                  placeholder="请输入学号"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 姓名输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="name"
                  className="block text-sm font-medium text-gray-700"
                >
                  姓名 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="name"
                  name="name"
                  type="text"
                  value={form.name}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, name: e.target.value }))
                  }
                  placeholder="请输入姓名"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 性别选择 */}
              <div className="space-y-2">
                <Label
                  htmlFor="gender"
                  className="block text-sm font-medium text-gray-700"
                >
                  性别
                </Label>
                <select
                  id="gender"
                  value={form.gender}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, gender: e.target.value }))
                  }
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none px-3"
                >
                  {genders.map((gender) => (
                    <option key={gender} value={gender}>{gender}</option>
                  ))}
                </select>
              </div>

              {/* 年龄输入 */}
              <div className="space-y-2">
                <Label
                  htmlFor="age"
                  className="block text-sm font-medium text-gray-700"
                >
                  年龄
                </Label>
                <Input
                  id="age"
                  name="age"
                  type="number"
                  value={form.age}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, age: parseInt(e.target.value) || 18 }))
                  }
                  placeholder="请输入年龄"
                  min="16"
                  max="100"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 专业选择 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="major"
                  className="block text-sm font-medium text-gray-700"
                >
                  专业
                </Label>
                <select
                  id="major"
                  value={form.major}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, major: e.target.value }))
                  }
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none px-3"
                >
                  <option value="">请选择专业</option>
                  {majors.map((major) => (
                    <option key={major} value={major}>{major}</option>
                  ))}
                </select>
              </div>

              {/* 班级输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="className"
                  className="block text-sm font-medium text-gray-700"
                >
                  班级
                </Label>
                <Input
                  id="className"
                  name="className"
                  type="text"
                  value={form.className}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, className: e.target.value }))
                  }
                  placeholder="请输入班级"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 入学年份选择 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="admissionYear"
                  className="block text-sm font-medium text-gray-700"
                >
                  入学年份
                </Label>
                <Input
                  id="admissionYear"
                  name="admissionYear"
                  type="text"
                  value={form.admissionYear}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, admissionYear: e.target.value }))
                  }
                  placeholder="YYYY"
                  maxLength={4}
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 手机号输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="phone"
                  className="block text-sm font-medium text-gray-700"
                >
                  手机号 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <Input
                    id="phone"
                    name="phone"
                    type="tel"
                    value={form.phone}
                    onChange={(e) =>
                      setForm((prev) => ({ ...prev, phone: e.target.value }))
                    }
                    placeholder="请输入手机号"
                    className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                  />
                </div>
              </div>

              {/* 邮箱输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="email"
                  className="block text-sm font-medium text-gray-700"
                >
                  邮箱
                </Label>
                <Input
                  id="email"
                  name="email"
                  type="email"
                  value={form.email}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, email: e.target.value }))
                  }
                  placeholder="请输入邮箱"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 密码输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="password"
                  className="block text-sm font-medium text-gray-700"
                >
                  密码 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="password"
                  name="password"
                  type="password"
                  value={form.password}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, password: e.target.value }))
                  }
                  placeholder="请设置密码（至少6位）"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 确认密码输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="confirmPassword"
                  className="block text-sm font-medium text-gray-700"
                >
                  确认密码 <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  value={form.confirmPassword}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, confirmPassword: e.target.value }))
                  }
                  placeholder="请再次输入密码"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>

              {/* 地址输入 */}
              <div className="space-y-2 col-span-2">
                <Label
                  htmlFor="address"
                  className="block text-sm font-medium text-gray-700"
                >
                  家庭地址
                </Label>
                <Input
                  id="address"
                  name="address"
                  type="text"
                  value={form.address}
                  onChange={(e) =>
                    setForm((prev) => ({ ...prev, address: e.target.value }))
                  }
                  placeholder="请输入家庭地址"
                  className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
                />
              </div>
            </div>

            {/* 消息提示 */}
            {msg && (
              <div className={`p-3 rounded-lg shadow-sm animate-fade-in ${msg.includes('成功') ? 'bg-green-50 border border-green-200' : 'bg-red-50 border border-red-200'}`}>
                <Text className={`text-sm font-medium ${msg.includes('成功') ? 'text-green-700' : 'text-red-700'}`}>{msg}</Text>
              </div>
            )}

            {/* 操作按钮 */}
            <div className="space-y-3">
              <Button
                variant="primary"
                onClick={() => {
                  if (validateForm()) {
                    sendVerificationCode(form.phone);
                  }
                }}
                disabled={loading || !form.phone || !form.studentId || !form.name || !form.password || !form.confirmPassword}
                className="h-12 w-full px-4 py-2 rounded-lg bg-gradient-to-r from-green-600 to-teal-600 text-white font-medium shadow-md hover:from-green-700 hover:to-teal-700 transition-all duration-200 focus:ring-4 focus:ring-teal-200 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <div className="flex items-center justify-center space-x-2">
                    <Spinner size="sm" className="text-white" />
                    <span>处理中...</span>
                  </div>
                ) : (
                  '注册'
                )}
              </Button>

              <div className="flex justify-center">
                <Button
                  variant="link"
                  onClick={() => navigate('/login')}
                  className="text-sm text-teal-600 hover:text-teal-800 hover:bg-teal-50 px-3 py-1 rounded-md transition-colors"
                >
                  已有账号？立即登录
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 验证码验证对话框 */}
      <Dialog open={showVerification} onOpenChange={setShowVerification}>
        <DialogContent size="sm" className="rounded-2xl border border-gray-200 shadow-xl">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold text-gray-900">验证身份</DialogTitle>
            <DialogDescription className="text-gray-600">
              为了确保您的账户安全，请输入发送到您手机的验证码
            </DialogDescription>
          </DialogHeader>

          <div className="py-6 space-y-5">
            <div className="space-y-2">
              <Label htmlFor="verification-code" className="font-medium text-gray-700">验证码</Label>
              <Input
                id="verification-code"
                value={userInputCode}
                onChange={(e) => setUserInputCode(e.target.value)}
                placeholder="请输入6位验证码"
                maxLength={6}
                className="h-12 w-full rounded-lg border-gray-300 focus:ring-2 focus:ring-teal-500 focus:border-teal-500 transition-all outline-none"
              />
              <div className="text-xs text-gray-500">
                测试验证码：{verificationCode}
              </div>
            </div>

            <div className="text-center">
              {countdown > 0 ? (
                <Text className="text-sm text-gray-600 font-medium">
                  验证码已发送，{countdown}秒后可重新发送
                </Text>
              ) : (
                <Button 
                  variant="link" 
                  onClick={resendCode} 
                  className="text-sm text-teal-600 hover:text-teal-800 hover:bg-teal-50 px-3 py-1 rounded-md transition-colors"
                >
                  重新发送验证码
                </Button>
              )}
            </div>
          </div>

          <DialogFooter className="space-x-3">
            <Button
              variant="outline"
              onClick={() => setShowVerification(false)}
              className="px-4 py-2 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 transition-colors"
            >
              取消
            </Button>
            <Button
              variant="primary"
              onClick={verifyCode}
              disabled={userInputCode.length !== 6}
              className="px-4 py-2 rounded-lg bg-gradient-to-r from-green-600 to-teal-600 text-white hover:from-green-700 hover:to-teal-700 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              验证
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}